package com.nearby.demand.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.nearby.demand.R;
import com.nearby.demand.adapter.AuthorAdapter;
import com.nearby.demand.adapter.listener.OnItemClickListener;
import com.nearby.demand.db.Demand;
import com.nearby.demand.ui.UiWorldDetail;
import com.nearby.demand.widget.ImageCycleView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

//消息
public class FragmentR extends BaseFragment {
    private Activity ctx;
    private View layout, layout_head;
    private TextView toolbar_title ;

    @Override
    protected void lazyLoad() {


    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void onVisible() {
        super.onVisible();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }
    public void initDemands() {
        demands = new ArrayList<>();
        for (int i = 0 ; i <10;i++){
            demands.add(new Demand());
        }

    }
    RecyclerView recycler_view;
    PtrClassicFrameLayout mPtrFrame;
    List<Demand> demands;
    AuthorAdapter authorAdapter;
    private ImageCycleView mAdView;
    private ArrayList<String> mImageUrl = null;
    private ArrayList<String> mImageName = null;
    private String imageUrl1 = "http://img.zcool.cn/community/01a86f55b47ce232f875251f3a546e.jpg";
    private String imageUrl2 = "http://www.zhiyuanit.com/images/ymbanner01.jpg";
    private String imageUrl3 = "http://img.zcool.cn/community/01f515554b298c0000007cc2487aaa.jpg";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (layout == null) {
            ctx = this.getActivity();

            layout = ctx.getLayoutInflater().inflate(R.layout.index_main,
                    null);
            initDemands();

            mImageUrl = new ArrayList<String>();
            mImageUrl.add(imageUrl1);
            mImageUrl.add(imageUrl2);
            mImageUrl.add(imageUrl3);
            mImageName=new ArrayList<String>();
            mImageName.add("美女1号");
            mImageName.add("美女2号");
            mImageName.add("美女3号");
            mAdView = (ImageCycleView) layout.findViewById(R.id.ad_view);
            mAdView.setImageResources(mImageUrl,mImageName, mAdCycleViewListener);

            recycler_view = (RecyclerView) layout.findViewById(R.id.recycler_view);
            mPtrFrame = (PtrClassicFrameLayout) layout.findViewById(R.id.rotate_header_list_view_frame);
            mPtrFrame.setLastUpdateTimeRelateObject(this);
            mPtrFrame.setPtrHandler(new PtrDefaultHandler2() {

                @Override
                public void onRefreshBegin(PtrFrameLayout frame) {
                    // TODO Auto-generated method stub
                    mPtrFrame.refreshComplete();
                }

                @Override
                public void onLoadMoreBegin(PtrFrameLayout frame) {
                    // TODO Auto-generated method stub
                    mPtrFrame.refreshComplete();
                }

            });
            // the following are default settings
            mPtrFrame.setResistance(1.7f);
            mPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f);
            mPtrFrame.setDurationToClose(200);
            mPtrFrame.setDurationToCloseHeader(1000);
            // default is false
            mPtrFrame.setPullToRefresh(false);
            // default is true
            mPtrFrame.setKeepHeaderWhenRefresh(true);


            authorAdapter = new AuthorAdapter(demands);
            //            mAdapter.setOnItemClickListener(new OnItemClickListener() {
            //                @Override
            //                public void onClick(int position, View view, Object item) {
            //                    Demand items = (Demand) item;
            //                    Toast.makeText(getActivity(), "短" + items.getStPid(), Toast.LENGTH_SHORT).show();
            //
            //                }
            //            });
            authorAdapter.setOnItemClickListener(new OnItemClickListener<Demand>() {

                @Override
                public void onClick(View view, Demand item) {
                    Toast.makeText(getActivity(), "短" + item.getStPid(), Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getActivity(), UiWorldDetail.class).putExtra("toChatUsername", item.getStPid()));

                }
            });
            //
            //            mAdapter.setOnItemLongClickListener(new OnItemLongClickListener<Demand>() {
            //                @Override
            //                public void onLongClick(View view, Demand item) {
            //                    Toast.makeText(getActivity(), "长按", Toast.LENGTH_SHORT).show();
            //                }
            //            });
            recycler_view.setHasFixedSize(true);//固定尺寸
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);

            recycler_view.setLayoutManager(linearLayoutManager );
//                        recycler_view.addItemDecoration(new DividerItemDecoration(getActivity(),
//                                DividerItemDecoration.VERTICAL_LIST));
            recycler_view.setAdapter(authorAdapter);

        } else {
            ViewGroup parent = (ViewGroup) layout.getParent();
            if (parent != null) {
                parent.removeView(layout);
            }
        }
        return layout;
    }
    private ImageCycleView.ImageCycleViewListener mAdCycleViewListener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void onImageClick(int position, View imageView) {
            // TODO 单击图片处理事件

        }
        @Override
        public void displayImage(String imageURL,ImageView imageView) {


        }
    };
    @Override
    public void onResume() {
        super.onResume();
        mAdView.startImageCycle();
    }
    @Override
    public void onPause() {
        super.onPause();
        mAdView.pushImageCycle();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mAdView.pushImageCycle();
    }
    /**
     * 获取所有会话
     *
     * @param
     * @return +
     */
    private List<EMConversation> loadConversationsWithRecentChat() {
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager
                .getInstance().getAllConversations();
        List<EMConversation> list = new ArrayList<EMConversation>();
        // 过滤掉messages seize为0的conversation
        for (EMConversation conversation : conversations.values()) {
            if (conversation.getAllMessages().size() != 0)
                list.add(conversation);
        }
        // 排序
        sortConversationByLastChatTime(list);
        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     *
     * @param
     */
    private void sortConversationByLastChatTime(
            List<EMConversation> conversationList) {
        Collections.sort(conversationList, new Comparator<EMConversation>() {
            @Override
            public int compare(final EMConversation con1,
                               final EMConversation con2) {

                EMMessage con2LastMessage = con2.getLastMessage();
                EMMessage con1LastMessage = con1.getLastMessage();
                if (con2LastMessage.getMsgTime() == con1LastMessage
                        .getMsgTime()) {
                    return 0;
                } else if (con2LastMessage.getMsgTime() > con1LastMessage
                        .getMsgTime()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }


}
